from pathlib import Path

from auto_docx import ReportGenerator
from matplotlib import pyplot as plt
from pendulum import PendulumODE
from scipy.integrate import solve_ivp

OUTPUT_FOLDER = Path(__file__).parent
DOCX_TEMPLATE_PATH = OUTPUT_FOLDER.joinpath("docx_template.docx")
REPORT_OUTPUT_PATH = OUTPUT_FOLDER.joinpath("report.docx")
SCRIPT_TO_INSERT_PATH = OUTPUT_FOLDER.joinpath("main.py")
IMAGE_NAMES = [
    [
        "image_x_without_2nd_garmonic",
        "image_y_without_2nd_garmonic",
        "image_z_without_2nd_garmonic",
        "image_vx_without_2nd_garmonic",
        "image_vy_without_2nd_garmonic",
        "image_vz_without_2nd_garmonic",
    ],
    [
        "image_x_with_2nd_garmonic",
        "image_y_with_2nd_garmonic",
        "image_z_with_2nd_garmonic",
        "image_vx_with_2nd_garmonic",
        "image_vy_with_2nd_garmonic",
        "image_vz_with_2nd_garmonic",
    ],
]

TEMPORARY_IMAGE_PATHS = [
    {name: str(OUTPUT_FOLDER.joinpath(f"{name}.jpg")) for name in sublist}
    for sublist in IMAGE_NAMES
]

start_cond = [
    -18506451.872,
    13631552.917,
    11092785.277,
    1378.1602644,
    635.0801909,
    3077.6660707,
]
sol = solve_ivp(
    PendulumODE().pendulum_np, [0, 86400], start_cond, first_step=1, max_step=1
)

for fig_name, values_vector in zip(TEMPORARY_IMAGE_PATHS[0].values(), sol.y):
    fig = plt.figure()
    plt.grid(True)
    plt.plot(sol.t, values_vector, color="red")
    fig.savefig(fig_name, dpi=200)

sol = solve_ivp(
    PendulumODE().pendulum, [0, 86400], start_cond, first_step=1, max_step=1
)

for fig_name, values_vector in zip(TEMPORARY_IMAGE_PATHS[1].values(), sol.y):
    fig = plt.figure()
    plt.grid(True)
    plt.plot(sol.t, values_vector, color="red")
    fig.savefig(fig_name, dpi=200)

report_generator = ReportGenerator(
    DOCX_TEMPLATE_PATH,
    REPORT_OUTPUT_PATH,
    SCRIPT_TO_INSERT_PATH,
    TEMPORARY_IMAGE_PATHS,
)
report_generator.generate_report()

for temp_dict in TEMPORARY_IMAGE_PATHS:
    for key, value in temp_dict.items():
        try:
            file_to_delete = Path(str(value))
            file_to_delete.unlink()
        except FileNotFoundError:
            continue
        except Exception:
            continue
